################################################################################
## Group Identities and Parliamentary Debates: Replication package
## Fiva, Nedregård and Øien (2025)

# Description:

## Code to make left plot (a) of Figure 2: "Across-bloc divergence over time"

################################################################################

# Packages 

library(data.table)
library(ggplot2)


# Directories (the working directory is ./scripts, set by master.R)

data.dir <-  "../data/3_model_output"
fig.dir  <-  "../results/figures"

# data

totpi_sort <- fread(file = paste(data.dir, "bloc_com_placebo.csv", sep = "/"), drop = "sessions")
estimated_pi <- fread(paste(data.dir, "bloc_com.csv", sep = "/"), header=T)

sessions <- c(1982:2021)
vertical.lines <- c(1981.5, 1985.5, 1989.5, 1993.5, 1997.5,2001.5, 2005.5, 2009.5, 2013.5, 2017.5, 2021.5)

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#Bloc----
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

max_pi <- totpi_sort[,5]
min_pi <- totpi_sort[,95]
max_pi_90 <- totpi_sort[,10]
min_pi_90 <- totpi_sort[,90]

bounds <- as.data.frame(cbind(sessions, max_pi, min_pi)) 
bounds_90 <- as.data.frame(cbind(sessions, max_pi_90, min_pi_90))
bounds$ind <- rep(95, len=nrow(bounds))
bounds_90$ind <- rep(90, len=nrow(bounds_90))

colnames(bounds)[2] <- "max_pi"
colnames(bounds)[3] <- "min_pi"
colnames(bounds_90)[2] <- "max_pi"
colnames(bounds_90)[3] <- "min_pi"

bounds <- as.data.frame(rbind(bounds, bounds_90))

bounds$mean <-  rowMeans(totpi_sort)
estimated_pi <- rbind(estimated_pi, estimated_pi)
bounds$pi <- estimated_pi$pi



p <- ggplot(data=bounds, aes(y=pi, x=sessions, group=ind, fill=ind)) +
  # Estimated divergence
  geom_line() +
  geom_point(size = 5) +
  # Placebo estimates
  geom_line(data=bounds, aes(sessions, mean),linetype = "dashed") +
  geom_ribbon(aes(ymin=min_pi, ymax=max_pi), fill="darkgray", alpha=0.45, linetype=0) +
  # Elections
  geom_vline(xintercept = vertical.lines, colour="gray80", linewidth = 0.2) +
  
  # Axis
  scale_x_continuous(breaks = seq(from=1981, to=2021, by=4)) +
  scale_y_continuous(limits = c(0.5, 0.509), breaks=c(0.5, 0.503, 0.506, 0.509)) +
  # Labs
  labs(x ="Session", y = "Average divergence") +
  # Theme
  theme(
    panel.grid = element_blank(),
    legend.position = "none",
    legend.title = element_blank(),
    panel.background = element_rect(fill = "transparent"),
    plot.background = element_rect(fill = "transparent"),
    axis.ticks.length = unit(0, "lines"),
    axis.text.x = element_text(family = "Montserrat", size = 16, angle = 45, hjust = 1),
    axis.text.y = element_text(family = "Montserrat", size = 16),
    axis.title.y = element_text(family = "Montserrat", size = 16),
    axis.title.x = element_text(family = "Montserrat", size = 16),
    plot.title = element_text(size = 20)
  )

ggsave(plot = p, 
       file = paste(fig.dir, "fig2a.pdf", sep = "/"),
       width = 11, height = 9, pointsize = 12, device = cairo_pdf)

